import { useState, useEffect, useRef } from 'react';

/**
 * 同步设置react的useState的方法
 * @param params 数据参数
 * @returns 
 */
export const useSyncState = <T>(params: T): [T, (data: T, cb: Function | undefined) => void] => {
    /** 异步回调函数 */
    const context = useRef<Function | undefined>(undefined);
    /** 数据 */
    const [data, setData] = useState<T>(params);
    /** 设置数据方法 */
    const setDataSync = (newData: T, callBack: Function | undefined) => {
        setData((prev) => {
            context.current = callBack;
            return typeof newData === 'function' ? newData(prev) : newData
        })
    }

    useEffect(() => {
        if (context.current && typeof context.current === 'function') {
            context.current?.();
            context.current = undefined;
        }
    }, [data])

    return [data, setDataSync]
}